<?php


namespace App\Http\Controllers\Weapp;


use App\Model\GoodsCollect;
use App\Model\GoodsSku;
use App\Model\GoodsView;
use App\Model\OrderGoods;
use App\Tool\Ip;
use App\Tool\Json;
use Illuminate\Support\Facades\Redis;

class Goods extends Base
{


    /**
     *
     * 详情页面数据
     * Create by Peter
     * 2019/11/21 10:34:35
     * Email:904801074@qq.com
     * @return false|string
     */
    function detail()
    {

//        \DB::connection()->enableQueryLog();
        $id = request()->input('id');

        $sku_id = request()->input('sku_id');

        $data = \App\Model\Goods::with('goods_sku.goods_sku_detail')
            ->with('goods_sku.snapped_sku.snapped')
            ->with('collect')
            ->find($id);

//        $data->append('real_price');


        if (!$data) return Json::code(1, 'success', $data);


        $data = $data->toArray();


        $goods_sku = $data['goods_sku'];

        $specifications = [];
        foreach ($goods_sku as $key => $value) {

            $temp = [];


            foreach ($value as $k => $v) {


                $temp[$k] = $v;

            }

            foreach ($value['goods_sku_detail'] as $k => $v) {

                $temp['difference'][] = $v['value'];

                $specifications[$v['key']]['name'] = $v['key'];

                if (!in_array($v['value'], array_column($specifications[$v['key']]['item'] ?? [], 'name'))) $specifications[$v['key']]['item'][] = ['name' => $v['value']];


            }

            $data['sku']['difference'][] = $temp;

        }


        $data['sku']['specifications'] = array_values($specifications);

//        $data['sku_detail']=$sku_detail;

//        if($sku_id) $this->getSkuDetail($sku_id);

        $sku_detail = $this->getSkuDetail($sku_id);

        $data['sku_details'] = $sku_detail;


        return Json::code(1, 'success', $data);


    }


    private function getSkuDetail($id)
    {


        if (!$id) return [];

        $sku_detail = GoodsSku::with('goods_sku_detail')->where('id', $id)->first();

        if (!$sku_detail) return [];

        if (!$sku_detail->goods_sku_detail) return [];

        return $sku_detail->goods_sku_detail;


    }

    /**
     * 获取推荐商品
     * Create by Peter
     * 2019/11/27 13:42:10
     * Email:904801074@qq.com
     * @return false|string
     */
    function recommendGoods()
    {


//        $data = \App\Model\Goods::where('recommend', 1)
//            ->with('goods_sku')
//            ->get();


        $data=GoodsSku::whereHas('goods',function ($query){


            $query->where('recommend', 1);

        })->with('goods')->with('snapped_sku.snapped')->get();


        return Json::code(1, 'success', $data);
    }


    /**
     * 获取新品
     * Create by Peter
     * 2019/11/28 09:47:13
     * Email:904801074@qq.com
     * @return false|string
     */
    function getNewGoods()
    {

        $list = \App\Model\Goods::with('goods_sku')
            ->orderBy('id', 'desc')
            ->limit(\Config::get('goods.new_goods_limit'))
            ->get();


        return Json::code(1, 'success', $list);


    }

    /**
     * 获取购物车里选中物品数量
     * Create by Peter
     * 2019/12/10 11:27:29
     * Email:904801074@qq.com
     */
    function getShopCarNum()
    {


//        $user_id=resolve('weapp_user')['id']??null;


        $user_id = $this->getUserInfo(request()->header('token'));


        if (!$user_id) return Json::code(1, 'success', 0);

        $user_id = $user_id['id'];


        $num = \App\Model\ShopCar::where('user_id', $user_id)
            ->has('goods_sku')
//            ->where('status',1)
            ->count();


        return Json::code(1, 'success', $num);


    }

    /**
     * 商品收藏
     * Create by PeterYang
     * 2020/05/26 21:40:40
     * Email:904801074@qq.com
     * @return false|string
     */
    function collect_goods()
    {

        $user_id = resolve('weapp_user')['id'];

        $goods_id = request()->input('id');

        $goods = GoodsCollect::where('goods_id', $goods_id)
            ->where('user_id', $user_id)->first();

        if ($goods) {

            GoodsCollect::destroy($goods->id);

            return Json::code(1, 'success');
        }

        GoodsCollect::create([
            'user_id' => $user_id,
            'goods_id' => $goods_id
        ]);

        return Json::code(1, 'success');


    }


    /**
     * 商品点击计数
     * Create by Peter
     * 2020/05/15 09:35:59
     * Email:904801074@qq.com
     * @return false|string
     */
    function addView()
    {

        //最大缓存量
        $maxCache = 3;

        $id = request()->input('id');

        $this->saveGoodsView($id);

        $num = (int)(Redis::get('goods_view:' . $id));


        if ($num >= $maxCache) {


            $info = \App\Model\Goods::where('id', $id)->first();

            if (!$info) return Json::code(2, '商品未找到！');

            $info->increment('view', $maxCache);


            Redis::del('goods_view:' . $id);

        }

        Redis::incrby('goods_view:' . $id, 1);

        return Json::code(1, 'success');


    }


    /**
     * 存储商品点击流水
     * Create by Peter
     * 2020/05/20 14:36:42
     * Email:904801074@qq.com
     * @param $goods_id
     * @return bool
     */
    private function saveGoodsView($goods_id)
    {

        $info = $this->getUserInfo();

        if (!$info) return false;

        $user_id = $info['id'];

        GoodsView::updateOrCreate(
            ['user_id' => $user_id, 'goods_id' => $goods_id],
            [
                'goods_id' => $goods_id,
                'user_id' => $user_id,
                'ip' => Ip::getClientIp(),
                'time' => time()
            ]);


    }

    /**
     * Create by Peter
     * 2020/07/20 16:54:54
     * Email:904801074@qq.com
     * @return false|string
     */
    function hot()
    {


        $p = request()->input('p', 1);

        $size = 6;

        $offset = ($p - 1) * $size;

//        return 'SELECT  SUM(num) sum , goods_sku_id FROM order_goods GROUP BY goods_sku_id ORDER BY `sum` desc limit '.$offset.",".$size;

        $list_ = \DB::select('SELECT  SUM(num) sum , goods_sku_id FROM order_goods GROUP BY goods_sku_id ORDER BY `sum` desc limit ' . $offset . "," . $size);

//        return $list;


        if (!$list_) return Json::code(1, 'success', []);

        $goods_array = array_column($list_, 'goods_sku_id');

        $list = \App\Model\GoodsSku::whereIn('id', $goods_array)
            ->with('goods_sku_detail')
            ->with('snapped_sku.snapped')
            ->with('goods')
            ->has('goods')
            ->get();

        foreach ($list as $key => $value) {

            foreach ($list_ as $k => $v) {


                if ($value['id'] == $v->goods_sku_id) {

                    $list[$key]->num = $v->sum;
                }
            }

        }


        return Json::code(1, 'success', $list);
    }

}
